package com.multicampus.minishop.services.purchase.impl;

import java.util.ArrayList;
import java.util.HashMap;

import com.multicampus.minishop.common.SearchVO;
import com.multicampus.minishop.product.vo.ProductVO;
import com.multicampus.minishop.services.product.dao.ProductDAO;
import com.multicampus.minishop.services.purchase.PurchaseService;
import com.multicampus.minishop.services.purchase.dao.PurchaseDAO;
import com.multicampus.minishop.services.purchase.vo.PurchaseVO;

public class PurchaseServiceImpl implements PurchaseService {
	private PurchaseDAO dao;
	private ProductDAO prodDAO;
	
	public PurchaseServiceImpl() {
		super();
		dao = new PurchaseDAO();
		prodDAO = new ProductDAO();
	}
	public PurchaseVO addPurchase(PurchaseVO vo) throws Exception {
		try {
			dao.insertPurchase(vo);
		} catch (Exception e) {
			throw e;
		}
		return vo;
	}

	public PurchaseVO getPurchase(int tranNo) throws Exception {
		try {
			PurchaseVO vo = dao.findPurchase(tranNo);
			int prodNo = vo.getPurchaseProd().getProdNo();
			ProductVO purchaseProd = prodDAO.findProduct(prodNo);
			vo.setPurchaseProd(purchaseProd);
			return vo;
		} catch (Exception e) {
			throw e;
		}
	}

	public HashMap getPurchaseList(SearchVO vo, String buyerId) throws Exception{
		try {
			HashMap map = dao.getPurchaseList(vo, buyerId);
			ArrayList list = setProductionsFromIds((ArrayList) map.get("list"));
			map.put("list", list);
			return map;
		} catch (Exception e) {
			throw e;
		}
	}

	public HashMap getSaleList(SearchVO vo) throws Exception {
		try {
			HashMap map = dao.getSaleList(vo);
			ArrayList list = setProductionsFromIds((ArrayList) map.get("list"));
			map.put("list", list);
			return map;
		} catch (Exception e) {
			throw e;
		}
	}

	private ArrayList setProductionsFromIds(ArrayList list) throws Exception {
		try {
			ArrayList arrayList = new ArrayList();
			
			for (Object object : list) {
				PurchaseVO invo = (PurchaseVO) object;
				int prodNo = invo.getPurchaseProd().getProdNo();
				ProductVO pvo = prodDAO.findProduct(prodNo);
				invo.setPurchaseProd(pvo);
				arrayList.add(invo);
			}
			
			return arrayList;
			
		} catch (Exception e) {
			throw e;
		}
	}
	public void updateTranCode(PurchaseVO vo) throws Exception {
		try {
			dao.updateTranCode(vo);
		} catch (Exception e) {
			throw e;
		}

	}

	public void updatePurchase(PurchaseVO vo) throws Exception {
		try {
			dao.updatePurchase(vo);
		} catch (Exception e) {
			throw e;
		}

	}

}
